package com.xinyue.chat.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 *  处理心跳
 * @author wgs
 *
 */
public class HeartbeatHandler extends ChannelInboundHandlerAdapter{

	private final static int HEARTBEAT_LENGTH=8;
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		if(msg instanceof ByteBuf) {
			ByteBuf byteBuf = (ByteBuf)msg;
			byteBuf.markReaderIndex();
			byteBuf.readInt();
			int messageId = byteBuf.readInt();
			if(MessageIDEnum.HEARTBEAT.isMatch(messageId)) {
				ByteBuf response = ctx.alloc().directBuffer(HEARTBEAT_LENGTH);
				response.writeInt(HEARTBEAT_LENGTH);
				response.writeInt(messageId);
				ctx.writeAndFlush(response);
			} else {
				byteBuf.resetReaderIndex();
				ctx.fireChannelRead(msg);
			}
		} else {
			ctx.fireChannelRead(msg);
		}
	}
	
}
